<?php
require_once ("facebook.php");

class UserController extends Zend_Controller_Action {
	
	private $user;
	private $userCredentials;
	private $country;
	private $city;
	private $resetPasswordRequest;
	private $mailQueue;
	protected $_flashMessenger = null;
	
	public function init() {
		$this->user = new User ( );
		$this->userCredentials = new UserCredentials ( );
		$this->country = new Country ( );
		$this->city = new City ( );
		$this->resetPasswordRequest = new ResetPasswordRequest();
		$this->mailQueue = new MailQueue();
		
		$this->initView ();
		$this->_flashMessenger = $this->_helper->getHelper ( 'FlashMessenger' );
		$this->view->flashmsgs = $this->_flashMessenger->getMessages ();
	}
	
	public function indexAction() {
	
	}
	
	public function citylistajaxAction() {
		$this->_helper->viewRenderer->setNoRender (); //view info disabled
		$this->_helper->getHelper ( 'layout' )->disableLayout (); //template disabled

		$countryId = $this->getRequest ()->getParam ( 'countryId' );
		
		if ($countryId != 0)
			$cities = Country::getTopCityByCountryAsArray ( $countryId );
		else
			$cities = null;
		
		$list = $this->view->selectList ( $cities );
		
		$returnJson = array ("list" => $list, "exist" => ($cities != null && count ( $cities ) > 0) );
		echo Zend_Json::encode ( $returnJson );
	}
	
	public function regionlistajaxAction() {
		$this->_helper->viewRenderer->setNoRender (); //view info disabled
		$this->_helper->getHelper ( 'layout' )->disableLayout (); //template disabled
		

		$cityId = $this->getRequest ()->getParam ( 'cityId' );
		
		if ($cityId != 0)
			$cities = City::getSubCityAsArray ( $cityId );
		else
			$cities = null;
		
		$list = $this->view->selectList ( $cities, "region" );
		
		$returnJson = array ("list" => $list, "exist" => ($cities != null && count ( $cities ) > 0) );
		echo Zend_Json::encode ( $returnJson );
	}
	
	public function booklistajaxAction() {
		$this->_helper->viewRenderer->setNoRender (); //view info disabled
		$this->_helper->getHelper ( 'layout' )->disableLayout (); //template disabled
		

		$type = $this->getRequest ()->getParam ( 'type' );
		$uid = $this->getRequest ()->getParam ( 'uid' );
		$user = $this->user->findById ( $uid );
		
		$results = null;
		if ($type == "available")
			$results = User::getBooks ( $user, UserBookStatus::AVAILABLE );
		if ($type == "letout")
			$results = User::getBooks ( $user, UserBookStatus::LETOUT );
		if ($type == "sold")
			$results = User::getBooks ( $user, UserBookStatus::SOLD );
		
		$list = $this->view->bookFetchList ( $results, "myBooks", $user, $type );
		
		$returnJson = array ("list" => $list, "count" => count ( $results ) );
		echo Zend_Json::encode ( $returnJson );
	}
	
	/**
	 * By Passing $email to check if it's already registered
	 * Called by register.js 
	 */
	public function checkemailajaxAction() {
		
		$this->_helper->viewRenderer->setNoRender (); //view info disabled
		$this->_helper->getHelper ( 'layout' )->disableLayout (); //template disabled
		

		$email = $this->getRequest ()->getParam ( 'email' );
		
		$user = $this->user->findByEmail ( $email );
		echo isset ( $user );
	}
	
	/**
	 * Registe action.
	 */
	public function registerAction() {
		
		$config = Zend_Registry::get ( 'config' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/js/jquery.validate.min.js' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/js/register.js' );
		
		$form = new RegisterForm ( );
		$this->view->form = $form;
		if ($this->getRequest ()->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$name = trim ( $form->getValue ( "name" ) );
				$email = trim ( $form->getValue ( "email" ) );
				$password = trim ( $form->getValue ( "password" ) );
				$countryId = trim ( $form->getValue ( "country" ) );
				if ($form->getValue ( "region" ) != 0)
					$cityId = trim ( $form->getValue ( "region" ) );
				else
					$cityId = trim ( $form->getValue ( "city" ) );
				
				$registrationKey = $this->_helper->generator ( 32, 'alpha' );
				$data = array (User::NAME => $name, "email" => $email, "password" => md5 ( $password ), "location" => $cityId, "created" => $this->_helper->generator->generateCurrentTime (), "status" => UserStatus::PENDING, "registration_key" => $registrationKey );
				$user = $this->user->findByEmailAndPassword ( $email, $password );
				if (! isset ( $user )) {
					$db = Zend_Registry::get ( "db" );
					$db->beginTransaction ();
					$this->user->addUser ( $data );
					$message = EmailTemplate::getUserActivateMessage ( $email, $registrationKey );
					$this->_helper->swiftEmail->sendEmail ( $message, $email, Constant::SYS_NO_REPLY_EMAIL, EmailTemplate::SUBJECT_USER_ACTIVATE );
					$db->commit ();
					// TODO this should redirect to a registe incomplete page
					$msg = "The confirmation email is sent to " . $email;
					$this->_flashMessenger->addMessage ( $msg );
					$this->_redirect ( '/user/success' );
				
				} else {
					echo "User already registered!";
				}
			}
		}
	}
	
	public function successAction() {
		$this->view->messages = $this->_flashMessenger->getMessages ();
	}
	
	/**
	 * User activate action.
	 */
	public function activateAction() {
		$key = $this->_getParam ( "key" );
		$email = $this->_getParam ( "email" );
		$user = $this->user->findUserByKeyAndEmail ( $key, $email );
		if ($user->status == UserStatus::PENDING) {
			$db = Zend_Registry::get ( "db" );
			$db->beginTransaction ();
			$this->user->updateUserStatus ( $user->id, UserStatus::ACTIVE, $this->_helper->generator->generateCurrentTime () );
			Activity::logActivity ( Activity::ACTIVATE_USER, $user->id, $user->id, $this->_helper->generator->generateCurrentTime () );
			$db->commit ();
			$this->_flashMessenger->addMessage ( "Your account " . $email . " is activated successfully! Log in to start!" );
			$this->_redirect ( "/user/login" );
		} else {
			echo "User not existed or can not be activate! It might because user has already be activated.";
		}
	}
	
	public function loginajaxAction() {
		
		$this->_helper->viewRenderer->setNoRender (); //view info disabled
		$this->_helper->getHelper ( 'layout' )->disableLayout (); //template disabled
		

		$email = $this->getRequest ()->getParam ( 'email' );
		$password = $this->getRequest ()->getParam ( 'password' );
		
		$user = new User ( );
		$auth = Zend_Auth::getInstance ();
		$authAdapter = new Zend_Auth_Adapter_DbTable ( $user->getAdapter (), 'user', 'email', 'password', 'md5(?) AND status="active"' );
		$authAdapter->setIdentity ( $email )->setCredential ( $password );
		$result = $auth->authenticate ( $authAdapter );
		if ($result->isValid ()) {
			$storage = new Zend_Auth_Storage_Session ( );
			$storage->write ( $authAdapter->getResultRowObject () );
			Zend_Registry::set ( 'userData', $user );
			$this->user->updateLastAccess ( $this->_helper->user->getUserData ()->id, $this->_helper->generator->generateCurrentTime () );
			echo true;
		} else {
			echo false;
		}
	}
	
	/**
	 * Login action.
	 */
	public function loginAction() {
		$config = Zend_Registry::get ( 'config' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/js/jquery.validate.min.js' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/js/register.js' );
		
		if (! $this->_helper->user->isLoggedIn ()) {
			
			$next = $this->_getParam ( "next" );
			$form = new LoginForm ( $next );
			
			$this->view->form = $form;
			$this->view->next = $next;
//			if ($this->getRequest ()->isPost ()) {
//				if ($form->isValid ( $_POST )) {
//					$user = new User ( );
//					$data = $form->getValues ();
//					$auth = Zend_Auth::getInstance ();
//					$authAdapter = new Zend_Auth_Adapter_DbTable ( $user->getAdapter (), 'user', 'email', 'password', 'md5(?) AND status="active"' );
//					$authAdapter->setIdentity ( $data ['email'] )->setCredential ( $data ['password'] );
//					$result = $auth->authenticate ( $authAdapter );
//					if ($result->isValid ()) {
//						$storage = new Zend_Auth_Storage_Session ( );
//						$storage->write ( $authAdapter->getResultRowObject () );
//						$this->user->updateLastAccess ( $this->_helper->user->getUserData ()->id, $this->_helper->generator->generateCurrentTime () );
//						
//						$returnUrl = $form->getValue ( "return" );
//						if (empty ( $returnUrl )) {
//							$this->_redirect ( '/' );
//						} else {
//							//small fix for NC
//							$returnUrl = str_replace ( "/heyidlebooks/public", "", $returnUrl );
//							
//							$this->_redirect ( $returnUrl );
//						}
//					} else {
//						echo "Incorrect email or password";
//					}
//				}
//			}
		} else {
			$this->_redirect ( "/" );
		}
	}
	
	/**
	 * Logout action.
	 */
	public function logoutAction() {
		$config = Zend_Registry::get ( "config" );
		$hasFacebookCredential = User::checkUserAuthProvider ( $this->_helper->user->getUserData (), AuthProvider::FACEBOOK );
		if (! empty ( $hasFacebookCredential )) {
			$facebook = new Facebook ( array ('appId' => $config->facebook->app->appId, 'secret' => $config->facebook->app->secretKey, 'cookie' => true, 'domain' => $config->facebook->app->domain ) );
			$storage = new Zend_Auth_Storage_Session ( );
			$storage->clear ();
			Zend_Registry::set ( 'userData', null );
			Zend_Session::destroy ( true, false );
			$url = $facebook->getLogoutUrl ( array ("next" => $config->baseurl ) );
			$this->_redirect ( $url );
		}
		$storage = new Zend_Auth_Storage_Session ( );
		$storage->clear ();
		Zend_Registry::set ( 'userData', null );
		Zend_Session::destroy ( true, false );
		$this->_redirect ( '/' );
	}
	
	/*
	 * get uid to check if it's the same as logged in user
	 * */
	
	function checkuid() {
		$uid = $this->_getParam ( "uid" );
		$id = $this->_helper->user->getUserData ()->id;
		$myself = ($uid == $id) || (empty ( $uid ));
		
		if (! empty ( $uid ))
			$user = $this->user->findById ( $uid );
		else
			$user = $this->user->findById ( $id );
		
		if (empty ( $user )) {
			throw new Zend_Exception ( "User not found!" );
		}
		
		return array ("user" => $user, "myself" => $myself );
	}
	
	/*
	 * profile action
	 * */
	public function profileAction() {
		$array = $this->checkuid ();
		$user = $array ["user"];
		
		$this->view->user = $user;
		$this->view->myself = $array ["myself"];
		$activities = User::getActivityByUser ( $user );
		$this->view->activities = $this->_helper->activity ( $activities );
		$this->view->books = User::getBooks ( $user, UserBookStatus::AVAILABLE );
		
		$this->view->pageTitle = $user->name . "'s Profile";
		$desc = $user->name . "|" . $user->introduction;
		foreach ( $this->view->books as $book ) {
			$desc .= $book->name . ",";
		}
		$this->view->pageDesc = $desc;
	
	}
	
	public function profilebooksAction() {
		$array = $this->checkuid ();
		$user = $array ["user"];
		$this->view->myself = $array ["myself"];
		
		$this->view->user = $user;
		$this->view->books = User::getBooks ( $user, UserBookStatus::AVAILABLE );
		
		$this->view->pageTitle = $user->name . "'s Books";
		$desc = "";
		foreach ( $this->view->books as $book ) {
			$desc .= $book->name . ",";
		}
		$this->view->pageDesc = $desc;
	}
	
	/**
	 * Show user's book list.
	 */
	public function booklistAction() {
		$config = Zend_Registry::get ( 'config' );
		$this->view->headScript ()->appendFile ( $config->baseurl . '/js/myBookList.js' );
		
		//$availableBooks = User::getBooks ( $user, UserBookStatus::AVAILABLE );
		

		$array = $this->checkuid ();
		$user = $array ["user"];
		$this->view->myself = $array ["myself"];
		if (! $array ["myself"])
			$this->_redirect ( "/user/booklist" );
		$this->view->user = $user;
		$this->view->pageTitle = $user->name . "'s Books";
		// $this->view->availableBooks = $availableBooks;
	}
	
	/**
	 * User setting action.
	 */
	public function settingsAction() {
		if ($this->_helper->user->isLoggedIn ()) {
			
			$config = Zend_Registry::get ( 'config' );
			$this->view->headScript ()->appendFile ( $config->baseurl . '/js/jquery.validate.min.js' );
			$this->view->headScript ()->appendFile ( $config->baseurl . '/js/register.js' );
			
			$uploadDir = $config->upload->file->dir;
			$thumbnailWidth = $config->upload->image->thumbnail->width;
			$thumbnailHeight = $config->upload->image->thumbnail->height;
			$originalWidth = $config->upload->image->target->width;
			$originalHeight = $config->upload->image->target->height;
			
			$user = $this->user->findById ( $this->_helper->user->getUserData ()->id );
			// if id parameter is given, then show user setting for given user id.
			$user_id = $this->_getParam ( "id" );
			if (! empty ( $user_id )) {
				$user = $this->user->findById ( $user_id );
			}
			
			if (empty ( $user )) {
				throw new Zend_Exception ( "User is not found!" );
			}
			
			$form = new UserSettings ( $user, $uploadDir );
			$this->view->user = $user;
			$this->view->form = $form;
			
			$this->view->pageTitle = $user->name . "'s Settings";
			
			if ($this->getRequest ()->isPost ()) {
				if ($form->isValid ( $_POST )) {
					$fileNameFromForm = $form->photo->getFileName ( null, false );
					$hasUploadFile = false;
					if ($form->photo->isUploaded ()) {
						if ($form->photo->receive ()) {
							$originalFilename = $form->photo->getFileName ( null, false );
							$srcFileName = $uploadDir . "/" . $originalFilename;
							$thumbnailFileName = $uploadDir . "/thumbnail/" . $originalFilename . ".jpg";
							$this->cropImage ( $thumbnailWidth, $thumbnailHeight, $srcFileName, 'jpg', $thumbnailFileName );
							$this->cropImage ( $originalWidth, $originalHeight, $srcFileName, 'jpg', $srcFileName . ".jpg" );
							Unlink ( $uploadDir . "/" . $originalFilename );
							$hasUploadFile = true;
						}
					}
					if ($form->getValue ( "region" ) != 0)
						$cityId = trim ( $form->getValue ( "region" ) );
					else
						$cityId = trim ( $form->getValue ( "city" ) );
						
					//					if (User::checkUserAuthProvider($user, AuthProvider::FACEBOOK)) {
					//						$data = array(
					//						   User::INTRODUCTION => trim($form->getValue("introduction")),
					//                           User::LOCATION =>($form->getValue ( "region" ) != 0)? trim($form->getValue ( "region" )) : trim($form->getValue ( "city" ))
					//						);
					//					} else {
					$data = array (User::BIG_IMG => $hasUploadFile ? $originalFilename . ".jpg" : null, User::SQUARE_IMG => $hasUploadFile ? $originalFilename . ".jpg" : null, User::INTRODUCTION => trim ( $form->getValue ( "introduction" ) ), User::NAME => trim ( $form->getValue ( "name" ) ), User::LOCATION => ($form->getValue ( "region" ) != 0) ? trim ( $form->getValue ( "region" ) ) : trim ( $form->getValue ( "city" ) ) );
					//					}
					$this->user->updateUserSettings ( $user->id, $data );
					$this->_flashMessenger->addMessage ( "Your personal info is updated successfully." );
					$this->_redirect ( "/user/settings" );
				}
			}
		} else {
			$this->_redirect( "/user/login?next=".urlencode($this->_helper->generator->getCurrentURI()) );
		}
	}
	
	/**
	 * User location action.
	 */
	public function locationAction() {
		
		$this->_helper->getHelper ( 'layout' )->disableLayout (); //template disabled
		

		if ($this->_helper->user->isLoggedIn ()) {
			$user = $this->user->findById ( $this->_helper->user->getUserData ()->id );
			$form = new LocationLoggedIn ( $user );
			$this->view->form = $form;
		} else {
			$form = new LocationNonLoggedIn ( );
			$this->view->form = $form;
		}
	
	}
	
	public function locationajaxAction() {
		
		$this->_helper->viewRenderer->setNoRender (); //view info disabled
		$this->_helper->getHelper ( 'layout' )->disableLayout (); //template disabled
		

		if ($this->_helper->user->isLoggedIn ()) {
			$cityId = $this->getRequest ()->getParam ( 'cityId' );
			$userId = $this->_helper->user->getUserData ()->id;
			
			$data = array (User::LOCATION => ($cityId) );
			$this->user->updateUserSettings ( $userId, $data );
		} else {
			$cityId = $this->getRequest ()->getParam ( 'cityId' );
			SessionUtil::setProperty ( Constant::KEY_CITY_ID, $cityId );
		}
	}
	
	private function cropImage($nw, $nh, $source, $stype, $dest) {
		$size = getimagesize ( $source );
		$w = $size [0];
		$h = $size [1];
		
		switch ($stype) {
			case 'gif' :
				$simg = imagecreatefromgif ( $source );
				break;
			case 'jpg' :
				$simg = imagecreatefromjpeg ( $source );
				break;
			case 'png' :
				$simg = imagecreatefrompng ( $source );
				break;
		}
		
		$dimg = imagecreatetruecolor ( $nw, $nh );
		$wm = $w / $nw;
		$hm = $h / $nh;
		$h_height = $nh / 2;
		$w_height = $nw / 2;
		
		if ($w > $h) {
			$adjusted_width = $w / $hm;
			$half_width = $adjusted_width / 2;
			$int_width = $half_width - $w_height;
			imagecopyresampled ( $dimg, $simg, - $int_width, 0, 0, 0, $adjusted_width, $nh, $w, $h );
		} elseif (($w < $h) || ($w == $h)) {
			$adjusted_height = $h / $wm;
			$half_height = $adjusted_height / 2;
			$int_height = $half_height - $h_height;
			
			imagecopyresampled ( $dimg, $simg, 0, - $int_height, 0, 0, $nw, $adjusted_height, $w, $h );
		} else {
			imagecopyresampled ( $dimg, $simg, 0, 0, 0, 0, $nw, $nh, $w, $h );
		}
		
		imagejpeg ( $dimg, $dest, 100 );
		imagedestroy ( $dimg );
	}
	
	/**
	 * Login with facebook.
	 * return loginResult with responseCode and responseMessage.
	 */
	public function fbloginAction() {
		$config = Zend_Registry::get ( "config" );
		
		$next = $this->_getParam("next");
		if (empty($next)) {
			$next = $config->baseurl;
		}
		$loggedInFacebookUser = $this->_helper->user->isLoggedInFacebookUser ();
		$facebook = $loggedInFacebookUser ["facebook"];
		// login or logout url will be needed depending on current user state.
		if ($loggedInFacebookUser ["loggedIn"]) {
			$facebookUser = $loggedInFacebookUser ["facebookUser"];
			$loginUrl = $facebook->getLoginUrl ( array ("next" => $config->baseurl . "/user/processfblogin?next=".urlencode($next), "req_perms" => "email"));
			$this->_redirect ( $loginUrl );
			// if already loggedIn
		//			$logoutUrl = $loggedInFacebookUser["facebook"]->getLogoutUrl(array("next"=>$config->baseurl."/user/processfblogout"));
		//			$this->view->logoutUrl = $logoutUrl;
		} else {
			$loginUrl = $facebook->getLoginUrl ( array ("next" => $config->baseurl . "/user/processfblogin?next=".urlencode($next), "req_perms" => "email"));
			$this->_redirect ( $loginUrl );
		}
		// This call will always work since we are fetching public data.
		$naitik = $facebook->api ( '/naitik' );
		$this->view->loggedInFacebookUser = $loggedInFacebookUser ["loggedIn"];
	}
	
	/**
	 * Process facebook user logout logic.
	 */
	public function processfblogoutAction() {
		$config = Zend_Registry::get ( "config" );
		$storage = new Zend_Auth_Storage_Session ( );
		$storage->clear ();
		$this->_redirect ( $config->baseurl );
	}
	
	/**
	 * Process facebook login logic.
	 */
	public function processfbloginAction() {
		$config = Zend_Registry::get ( "config" );
		$loggedInFacebookUser = $this->_helper->user->isLoggedInFacebookUser ();
		$next = $this->_getParam("next");
		
		// login or logout url will be needed depending on current user state.
		if ($loggedInFacebookUser ["loggedIn"]) {
			$facebook = $loggedInFacebookUser ["facebook"];
			$uid = $facebook->getUser ();
			$param = array ('method' => 'users.getinfo', 'uids' => $uid, 'fields' => 'profile_url, uid, name, username, email, pic_square, pic_big, current_location', 'callback' => '' );
			$userInfo = $facebook->api ( $param );
			$email = $userInfo [0] ["email"];
			$user = $this->user->findByEmail ( $email );
			
			$db = Zend_Registry::get ( "db" );
			$db->beginTransaction ();
			
			if (! isset ( $user )) {
				$data = array ("email" => $email, "name" => $userInfo [0] ["name"], "location" => $this->getFacebookUserLocation ( $userInfo [0] ["current_location"] ), "created" => $this->_helper->generator->generateCurrentTime (), "last_access" => $this->_helper->generator->generateCurrentTime (), "registration_key" => $uid, "big_img" => $userInfo [0] ["pic_big"], "square_img" => $userInfo [0] ["pic_square"], "status" => UserStatus::ACTIVE );
				$user = $this->user->addFacebookUser ( $data );
				Activity::logActivity ( Activity::ACTIVATE_USER, $user->id, $user->id, $this->_helper->generator->generateCurrentTime () );
				// update user credentials, if proper.
				$data = array ("user_id" => $user->id, "auth_provider" => AuthProvider::FACEBOOK, "auth_uid" => $uid, "created" => $this->_helper->generator->generateCurrentTime (), "status" => UserCredentialStatus::ACTIVE );
				$this->userCredentials->addCredential ( $data );
				$this->_flashMessenger->addMessage ( "You've registered successfully according to your facebook information." );
			} else {
				$data = array(
				    "email" => $email,
				    "last_access" => $this->_helper->generator->generateCurrentTime()
				);
				$this->user->addFacebookUser($data);
				$data = array ("user_id" => $user->id, "auth_provider" => AuthProvider::FACEBOOK, "auth_uid" => $uid, "created" => $this->_helper->generator->generateCurrentTime (), "status" => UserCredentialStatus::ACTIVE );
				$addnewcredential = $this->userCredentials->addCredential ( $data );
				if ($addnewcredential)
					$this->_flashMessenger->addMessage ( "Your facebook is now connected with your existing account because they have the same email." );
			
			}
			
			$db->commit ();
			$storage = new Zend_Auth_Storage_Session ( );
			$storage->write ( $user );
			
			$this->_redirect ( urldecode($next) );
		}
	}
	
	/**
	 * Facebook connect. Used when normal user want to connect to facebook.
	 */
	public function fbconnectAction() {
		if ($this->_helper->user->isLoggedIn ()) {
			$user = $this->_helper->user->getUserData ();
			$config = Zend_Registry::get ( "config" );
			$facebook = new Facebook ( array ('appId' => $config->facebook->app->appId, 'secret' => $config->facebook->app->secretKey, 'cookie' => true, 'domain' => $config->facebook->app->domain ) );
			$session = $facebook->getSession ();
			$logger = Zend_Registry::get ( "logger" );
			$me = null;
			$step = $this->_getParam ( "step" );
			if ($step == 2) {
				$uid = $facebook->getUser ();
				$param = array ('method' => 'users.getinfo', 'uids' => $uid, 'fields' => 'profile_url, uid, name, username, email, pic_square, pic_big, current_location', 'callback' => '' );
				$userInfo = $facebook->api ( $param );
				$email = $userInfo [0] ["email"];
				// if facebook email is not same as the logged in user, then it's wrong.
				if ($email != $user->email) {
					$logger->log ( "User " . $user->id . " is not allowed to logged in as facebook id " . $uid, Zend_Log::ERR );
					$this->_flashMessenger->addMessage ( "You are not allowed to connect with this facebook account ... " );
				} else {
					// update user credentials, if proper.
					$data = array ("user_id" => $user->id, "auth_provider" => AuthProvider::FACEBOOK, "auth_uid" => $uid, "created" => $this->_helper->generator->generateCurrentTime (), "status" => UserCredentialStatus::ACTIVE );
					$addnewcredential = $this->userCredentials->addCredential ( $data );
					if ($addnewcredential)
						$this->_flashMessenger->addMessage ( "You are now connected successfully with a facebook account." );
				}
			} else {
				$loginUrl = $facebook->getLoginUrl ( array ("next" => $config->baseurl . "/user/fbconnect/step/2" ) );
				$this->_redirect ( $loginUrl );
			}
			
			//			}
			$this->_redirect ( "/user/settings" );
		} else {
			$this->_redirect( "/user/login?next=".urlencode($this->_helper->generator->getCurrentURI()) );
		}
	}
	
	/**
	 * Get facebook user location from current location array.
	 * example:
	 * Array ( [city] => Stockholm [state] => Stockholms Lan [country] => Sweden [zip] => [id] => 106505586052951 [name] => Stockholm, Sweden )
	 *  
	 * @param $currentLocation
	 * @return city id
	 */
	private function getFacebookUserLocation($currentLocation) {
		// default stockholm
		$cityId = 1;
		if (! empty ( $currentLocation )) {
			$city = $this->city->findByName ( $currentLocation ["city"] );
			if (isset ( $city )) {
				$cityId = $city->id;
			}
		}
		return $cityId;
	}
	
	/**
	 * Forget password.
	 */
	public function forgetpasswordAction() {
		$form = new ForgetPassword ( );
		$this->view->form = $form;
		if ($this->getRequest ()->isPost ()) {
			if ($form->isValid ( $_POST )) {
				$email = trim ( $form->getValue ( "email" ) );
				$user = $this->user->findByEmail($email);
				if (isset($user) && !empty($user->password)) {
					$registrationKey = $this->_helper->generator ( 32, 'alpha' );
					$data = array(
					   "user_id" => $user->id,
					   "key" => $registrationKey,
					   "created" => $this->_helper->generator->generateCurrentTime()
					);
					$db = Zend_Registry::get("db"); 
					$db->beginTransaction();
					$this->resetPasswordRequest->addEntry($data);
					$extra = array(
					   "key" => $registrationKey,
					   "email" => $email
					);
					$message = EmailTemplate::getEmailMessage(Activity::RESET_PASSWORD, Constant::SYS_NO_REPLY_EMAIL, $user, $extra);
					$this->mailQueue->addToQueue(Activity::RESET_PASSWORD, EmailTemplate::SUBJECT_RESET_PASSWORD, Constant::SYS_NO_REPLY_EMAIL, $email, $message, $this->_helper->generator->generateCurrentTime());
					$db->commit();
				} else {
					$logger = Zend_Registry::get("logger");
					$logger->log("User by email: ".$email." is not found in the system.", Zend_Log::WARN);
				    echo "User not exist";
				}
			}
		}
	}
	
	public function resetpasswordAction() {
	   $key = $this->_getParam("key");
	   $resetRequest = $this->resetPasswordRequest->findActiveByKey($key);
	   if (isset($resetRequest)) {
	   	   $form = new ResetPassword();
	   	   $this->view->form = $form;
	   	   $db = Zend_Registry::get("db");
	   	   $db->beginTransaction();
	       $userId = $resetRequest->user_id;
	       
	       $db->commit();
	   } else {
	       echo "User requset is not valid any more.";
	   }
	}
}